package com.core.controller;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

/**
 * 继承此类的子类具备基本的CRUD
 * 
 * @author hexin
 * 
 * @param <M> Model
 */
public class BaseController<M extends Model<M>> extends Controller {
	public BaseController() {
		// 把class的变量保存起来，不用每次去取
		this.setModelClass(getClazz());
	}

	/**
	 * 获取M的class
	 * 
	 * @return M
	 */
	@SuppressWarnings("unchecked")
	public Class<M> getClazz() {
		Type t = getClass().getGenericSuperclass();
		Type[] params = ((ParameterizedType) t).getActualTypeArguments();
		return (Class<M>) params[0];
	}

	protected Class<M> modelClass;

	public Class<M> getModelClass() {
		return modelClass;
	}

	public void setModelClass(Class<M> modelClass) {
		this.modelClass = modelClass;
	}

	/**
	 * 通用分页查找
	 */
	public void getByPage() {
		Page<Record> list = Db
				.paginate(getParaToInt("pageNumber"), getParaToInt("pageSize"),
						"select *", "from " + getModelClass().getSimpleName()
								+ " order by id desc");
		renderJson(list);
	}

	/**
	 * 通用查找全部
	 */
	public void getAll() {
		renderJson(Db.find("select * from " + getModelClass().getSimpleName()
				+ " order by id asc;"));
	}

	/**
	 * 通用根据id查找
	 */
	public void getById() {
		Record info = Db.findById(getModelClass().getSimpleName(), getParaToInt("id"));
		renderJson(info);
	}
	
	/**
	 * 自定义的根据参数查找
	 * @param configName
	 * @param tableName
	 * @param pkName
	 * @return
	 */
	public Record getById2(String configName,String tableName,String pkName){
		int id = getParaToInt(0);
		Record info = Db.use(configName).findById(tableName, pkName, id);
		return info;
	}

	/**
	 * 通用新增
	 * 
	 * @throws Exception
	 */
	public void save() throws Exception {
		renderText((getModel(getModelClass())).save() + "");
	}

	/**
	 * 通用修改
	 * 
	 * @throws Exception
	 */
	public void update() throws Exception {
		renderText(getModel(getModelClass()).update() + "");
	}

	/**
	 * 通用删除
	 * 
	 * @throws Exception
	 */
	public void delete() throws Exception {
		renderText(getModel(getModelClass()).delete() + "");
	}
}